package com.zhu.rpc.client;


import com.zhu.rpc.MsgType;
import com.zhu.rpc.RpcProtocol;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class RpcRequest {
    private static Map<String,Channel> channelMap = new HashMap<>();
    public static Map<String,String> methodProvideMap = new HashMap<>();
    public static Map<String,CallType> methodCallTypeMap = new HashMap<>();

    private static Logger logger = LoggerFactory.getLogger(RpcRequest.class);
    public static void setNettyChannel(String serverName,Channel nettyChannel) {
        channelMap.put(serverName,nettyChannel);
    }

    public static void sendRpcRequestMsg(String methodName, StringBuilder msg,MsgType msgType){
//        msg.appendCodePoint()
        msg.insert(0,msgType.id);
        System.out.println("发送消息:"+msg);

        channelMap.get(methodProvideMap.get(methodName)).writeAndFlush(msg.toString()).addListener(future -> {
            if (future.isSuccess()){
                logger.debug("成功");
            }
        });
    }

    //设置方法的调用类型
    public static void setMethodCallType(Class cla){
        for (Method m :cla.getDeclaredMethods()) {
            CustomerMethod customerMethod = m.getAnnotation(CustomerMethod.class);
            String methodName = RpcProtocol.getConsumerMethodRpcName(m);
            CallType callType;
            if (m.getReturnType() == void.class){
                callType = CallType.OneWay;
            }else if (customerMethod != null){
                callType = customerMethod.callType();
            }else {
                callType = CallType.Sync;
            }
            methodCallTypeMap.put(methodName,callType);
        }
    }
    //设置方法的调用类型
    public static CallType getMethodCallType(String name){
        return methodCallTypeMap.get(name);
    }

}
